from rqalpha.apis import *
import time
from rqalpha.environment import Environment
from rqalpha.my_factors.reform_data import get_all_symbols_price_factor
from rqalpha import run_func


config = {
    "base": {
        "start_date": "2021-07-31",
        "end_date": "2021-07-31",
        "frequency": "tick",
        "accounts": {
            "stock": 100000
        }
    },

    "extra": {
        "log_level": "info",
    },

    "mod": {
        "my_backtest": {
            "enabled": True
        },
        "sys_analyser": {
            "enabled": True,
            "benchmark": "000300.XSHG",
            "plot": True,
            # "plot": False,
            "report_save_path": "C:\\Users\\huajia\Desktop\\rqalpha4\\rqalpha\\plot_result"
        },
        "sys_simulation": {
            "enabled": True,
            "matching_type": "best_own",
        },
        "sys_accounts": {
            "enabled": True,
            "validate_stock_position": False,
            "stock_t1": False
        },
        "incremental": {
            "enabled": True,
            "strategy_id": "1",
            # 是否启用 csv 保存 feeds 功能，可以设置为 MongodbRecorder
            "recorder": "CsvRecorder",
            # 持久化数据输出文件夹
            "persist_folder": "C:\\Users\huajia\\Desktop\\rqalpha4\\rqalpha\\incremental_result",
            # "persist_folder": None,
            # mongodb
            "mongo_url": "mongodb://localhost",
            "mongo_dbname": "rqalpha_records",
        }
    }
}


def run_bt(config, my_defines):
    # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
    data = None
    factor1 = None

    def init(context):
        logger.info("init------------")
        nonlocal data, factor1
        _env = Environment.get_instance()
        symbol = _env.config.base.all_symbols_mapping
        # print(symbol)
        data = _env.data_source.ticks_data
        # print(data.head(10))
        # print(data[data['datetime'] >= pd.to_datetime('2022-01-10 14:50:00')].head(5))
        logger.info("get factors---")
        factor1 = get_all_symbols_price_factor(data)
        # print(factor1)
        context.s1 = symbol
        context.queue = {}
        context.all_queue = None
        # time.sleep(500)
        if context.all_queue is None:
            context.all_queue = set(factor1['order_book_id'].unique().tolist())
        else:
            context.all_queue = context.all_queue | set(factor1['order_book_id'].unique().tolist())
        update_universe(context.s1)
        subscribe(context.s1)

    def before_trading(context):
        print('before trading---------------')
        nonlocal factor1
        # print(factor1)

    def handle_tick(context, tick):
        # print(tick)
        nonlocal factor1
        for stock in context.all_queue:
            if stock == tick.order_book_id:
                dt = tick.datetime
                mask = (factor1['order_book_id'] == stock) & (factor1['datetime'] == dt)
                this_factor = factor1[mask]
                # if not this_factor.empty:
                    # print(this_factor)
                if not this_factor.empty and stock not in context.queue:
                    # print('==========', stock, context.now, dt)
                    order_shares(stock, -100)
                    context.queue[stock] = dt
                    context.all_queue.add(stock)
                if not this_factor.empty and stock in context.queue:
                    pass
                if stock in context.queue and dt.date() > context.queue[stock].date() and \
                        dt.strftime('%H:%M:%S') >= '09:30:00':
                    order_shares(stock, 100)
                    context.all_queue.add(stock)
                    del context.queue[stock]

    def after_trading(context):
        print('after trading----------------')
        nonlocal data, factor1
        # logger.info(data.tail(3))
        # print(factor1)
    run_func(config=config, init=init, before_trading=before_trading, handle_tick=handle_tick,
             after_trading=after_trading, my_defines=my_defines)


